package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/panjf2000/ants/v2"
	"sgo/app/system/dto"
	"sgo/app/system/service"
	"sgo/common/response"
	"sgo/scontext"
	"strconv"
)

type UserController struct{}

func (uc UserController) List(ctx *gin.Context, sc *scontext.SgoContext) response.Response {

	userList := service.SystemUserService.List(ctx, sc)
	ants.Submit(func() {
		panic("error...")
	})
	return response.OkWithData(userList)
}

func (uc UserController) Delete(ctx *gin.Context, sc *scontext.SgoContext) response.Response {
	idStr := ctx.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		return response.FailWithMessage("删除失败")
	}
	service.SystemUserService.Delete(ctx, sc, id)
	return response.Ok()
}

func (uc UserController) Create(ctx *gin.Context, sc *scontext.SgoContext) response.Response {
	userDTO := new(dto.UserDTO)

	_ = ctx.ShouldBindWith(userDTO, binding.JSON)

	err := sc.Validator.Validate.Struct(userDTO)

	if err != nil {
		return response.Error(err)
	}

	service.SystemUserService.Create(ctx, sc, userDTO)

	return response.Ok()
}

func (uc UserController) Update(ctx *gin.Context, sc *scontext.SgoContext) response.Response {
	userDTO := new(dto.UserDTO)

	_ = ctx.ShouldBindWith(userDTO, binding.JSON)

	err := sc.Validator.Validate.Struct(userDTO)

	if err != nil {
		return response.Error(err)
	}

	service.SystemUserService.Update(ctx, sc, userDTO)

	return response.Ok()
}

// 事务控制实例

func (uc UserController) CreateAndDelete(ctx *gin.Context, sc *scontext.SgoContext) response.Response {
	userDTO := new(dto.UserDTO)

	_ = ctx.ShouldBindWith(userDTO, binding.JSON)

	err := sc.Validator.Validate.Struct(userDTO)

	if err != nil {
		return response.Error(err)
	}

	service.SystemUserService.CreateAndDelete(ctx, sc, userDTO)

	return response.Ok()
}
